#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: user.py
@contact: zwb15083976291@163.com
@time: 2021/11/11
"""
from django.db.models import Q
from rest_framework import serializers

from common.models import BlogUser
from utils.serializers import SpecifySerializeFieldModelSerializer, SpecifySerializeFieldSerializer
from utils.serializers.serializer import UpdateBaseSerializeMethodMixin


class AdminSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    class Meta:
        model = BlogUser
        fields = "__all__"


class AdminTokenSerializer(SpecifySerializeFieldModelSerializer):
    class Meta:
        model = BlogUser
        fields = ("id", "username", 'user_type')


class AdminLoginSerializer(SpecifySerializeFieldSerializer):
    username = serializers.CharField(min_length=2)
    password = serializers.CharField(min_length=6)

    def validate(self, attrs):
        admin = BlogUser.objects.filter(Q(username=attrs["username"]) & Q(password=attrs["password"])).first()
        if not admin:
            raise serializers.ValidationError("用户名或密码错误")
        self.context["admin"] = admin
        return attrs
